package com.demo

import java.text.MessageFormat

/**
  * 变长参数
  * Created by adengdeng on 2017/8/5 
  */
object Demo2_9 {

  def sum(args: Int*) = {
    var result = 0
    for (arg <- args) result += arg
    result
  }


  def main(args: Array[String]): Unit = {

    val a = sum(1, 2, 3, 4, 5)
    //错误写法。 1 to 4 返回的是sqe对象，也就是个队列
    //val b = sum(1 to 4)

    //追加: _*，将1 to 5 当做参数序列处理 . "_"表示通配符，这里类似sum方法中的"Int*"
    val b = sum(1 to 5: _*)

    println(a)
    println(b)

    //当你调用变长参数且参数类型为Object的java方法，需要手工对基本类型进行转换
    //  public static String format(String pattern, Object ... arguments) {
    val str = MessageFormat.format("The answer to {0} is {1}", "A", 42.asInstanceOf[AnyRef])
    println(str)

  }
}
